"use strict";

var winston = require('winston'),
    C = require('../common'),
    MongoDB = require('winston-mongodb').MongoDB,
    Mail = require('winston-mail').Mail;

var TransportsTable = {
    console: winston.transports.Console,
    file: winston.transports.File,
    mongodb: MongoDB,
    mail: Mail
};

function processTransports(options) {
    if (options.transports) {

        var transports = options.transports,
            transportsObject = [];

        options = C._.omit(options, 'transports');

        C._.each(transports, function (transport, index) {

            transport.type || C.throwRequired('Logger transport type');

            if (!TransportsTable[transport.type]) {
                throw new C.Error.ConfigError(
                    'Logger transport type', 'Unsupported item value.');
            }

            var TransportClass = TransportsTable[transport.type];
            transportsObject.push(new TransportClass(transport.options));
        });

        options.transports = transportsObject;
    }

    return options;
}

module.exports = {

    type: 'service',

    processTransports: processTransports,

    load: function (owner, loggers, cb) {
        var _pool = {};

        owner.registerService('logger', function (name) {
            if (name in _pool) return _pool[name];
            return (_pool[name] = new (winston.Logger)(processTransports(loggers[name])));
        });

        cb();
    }
};


